import LocalStorage from "../engine/LocalStorage";
import { Logger } from "../engine/Logger";
import Uint8ArrayHelper from "../engine/Uint8ArrayHelper";
import { GameConfig } from "../game/config/GameConfig";
import { UserModel } from "../game/model/UserModel";
import { UIHelper } from "../game/util/UIHelper";
import { SocketClient } from "../net/SocketClient";
import { VoiceSdkHelper } from "./VoiceSdkHelper";
import { WechatSdkManager } from "./WechatSdkManager";


const Native_Android_Class: string = "com/jhaosdk/NativeSdkHelper"
const Native_IOS_Class: string = "NativeSdkHelper"

export class NativeSdkHelper {

    public static Channel_Type = {
        Web: 0,
        Ios: 1,
        android: 2,
    }

    public static channel: number = 1;
    private static upload_pic_type: number = GameConfig.upload_pic_type.HeadImg

    public static init() {
        window["NativeSdkHelper"] = NativeSdkHelper;

        WechatSdkManager.init()
        VoiceSdkHelper.init()
        if (NativeSdkHelper.isIos()) {
            ////保持屏幕常亮
            NativeSdkHelper.channel = NativeSdkHelper.Channel_Type.Ios
            jsb.reflection.callStaticMethod(Native_IOS_Class, "keyScreenLight:", "")
        } else if (NativeSdkHelper.isAndroid()) {
            NativeSdkHelper.channel = NativeSdkHelper.Channel_Type.android
            jsb.reflection.callStaticMethod("org/cocos2dx/lib/Cocos2dxHelper", "setKeepScreenOn", "(Z)V", true);
        } else {
            NativeSdkHelper.channel = NativeSdkHelper.Channel_Type.Web
        }
        // setTimeout(() => {
        //     this.showFloatWindowNewWay()
        // }, 1000);
    }

    public static isAndroid() {
        if (cc.sys.isNative) {
            if (cc.sys.os == cc.sys.OS_ANDROID || cc.sys.os == cc.sys.OS_LINUX) {
                return true
            }
        }
    }

    public static isIos() {
        if (cc.sys.isNative) {
            if ((cc.sys.os == cc.sys.OS_IOS || cc.sys.os == cc.sys.OS_OSX)) {
                return true;
            }
        }
        return false;
    }

    /**
    * 原生平台copy功能
    * @param copyStr 
    */
    public static copyToClipBoard(copyStr: string) {
        if (this.isAndroid()) {
            jsb.reflection.callStaticMethod("org/cocos2dx/lib/Cocos2dxHelper", "copyTextToClipboard", "(Ljava/lang/String;)V", copyStr);
        }
        else if (this.isIos()) {
            jsb.reflection.callStaticMethod(Native_IOS_Class, "copy:", copyStr);
        }
        else {
            Logger.log('复制', copyStr);
            var textArea = document.getElementById("clipBoard");
            if (textArea === null) {
                textArea = document.createElement("textarea");
                textArea.id = "clipBoard";
                textArea.textContent = copyStr;
                document.body.appendChild(textArea);
            }
            textArea.select();
            try {
                const msg = document.execCommand('copy') ? 'successful' : 'unsuccessful';
                Logger.log("已经复制到剪贴板");
                document.body.removeChild(textArea);
            } catch (err) {
                Logger.log("复制到剪贴板失败");
            }
        }
    }

    public static vibrate() {
        if (this.isAndroid()) {
            jsb.reflection.callStaticMethod("org/cocos2dx/lib/Cocos2dxHelper", "vibrate", "(F)V", 1);
        }
        else if (this.isIos()) {
            jsb.reflection.callStaticMethod("NativeSdkHelper", "vibrate:", "");
        }
    }


    private static randomMachineId() {
        let machineId: string = LocalStorage.getItem("MachineID");
        if (machineId == null) {
            var mahineIdList: Array<string> = [];
            var data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            for (var i = 0; i < 16; i++) {
                mahineIdList.push(data.charAt(Math.random() * data.length));
            }
            machineId = mahineIdList.join("");
            machineId = "H5-" + machineId;
            LocalStorage.setItem("MachineID", machineId);
        }
        return machineId;
    }

    public static getUDID() {
        let machineId: string = "abcd"
        if (this.isAndroid()) {
            machineId = jsb.reflection.callStaticMethod(Native_Android_Class, "getUDID", "()Ljava/lang/String;");
        }
        else if (this.isIos()) {
            machineId = jsb.reflection.callStaticMethod(Native_IOS_Class, "getUDID:", "");
        } else {
            machineId = this.randomMachineId();
        }
        // Logger.info("getUDID", machineId);
        return machineId;
    }

    public static getAppVersion() {
        let appVersion: string = "1.0.0"
        if (this.isAndroid()) {
            appVersion = jsb.reflection.callStaticMethod("org/cocos2dx/lib/Cocos2dxHelper", "getVersion", "()Ljava/lang/String;");
        }
        else if (this.isIos()) {
            appVersion = jsb.reflection.callStaticMethod(Native_IOS_Class, "getAppVersion:", "");
        }
        // Logger.log("getAppVersion", appVersion)
        return appVersion;
    }

    public static getSystemVersion() {
        let sysVersion: string = "1.0.0"
        if (this.isAndroid()) {
            sysVersion = jsb.reflection.callStaticMethod("org/cocos2dx/lib/Cocos2dxHelper", "getSystemVersion", "()Ljava/lang/String;");
        }
        else if (this.isIos()) {
            sysVersion = jsb.reflection.callStaticMethod(Native_IOS_Class, "getSystemVersion:", "");
        }
        // Logger.log("getSystemVersion", sysVersion)
        return sysVersion;
    }

    public static getBundleName() {
        let bundleName: string = "com.jhao.bundle"
        if (this.isAndroid()) {
            bundleName = jsb.reflection.callStaticMethod("org/cocos2dx/lib/Cocos2dxHelper", "getPackageName", "()Ljava/lang/String;");
        }
        else if (this.isIos()) {
            bundleName = jsb.reflection.callStaticMethod(Native_IOS_Class, "getBundleName:", "");
        }
        // Logger.log("getBundleName", bundleName)
        return bundleName;
    }

    //获取手机型号
    public static getPhoneType() {
        let iphoneType: string = "web";
        if (this.isIos()) {
            iphoneType = jsb.reflection.callStaticMethod(Native_IOS_Class, "getIphoneType:", "");
        }
        else if (this.isAndroid()) {
            iphoneType = jsb.reflection.callStaticMethod("org/cocos2dx/lib/Cocos2dxHelper", "getDeviceModel", "()Ljava/lang/String;");
        }
        // Logger.log("获取手机型号====", iphoneType);
        return iphoneType
    }


    public static getLocation() {
        if (UserModel.instance.locationStr && UserModel.instance.locationStr != "") {
            this.setLocation(UserModel.instance.locationStr)
        } else {
            if (this.isIos()) {
                jsb.reflection.callStaticMethod(Native_IOS_Class, "getLocation:", "");
            }
            else if (this.isAndroid()) {
                jsb.reflection.callStaticMethod(Native_Android_Class, "getLocation", "()Ljava/lang/String;");
            } else {
                // this.setLocation("1,1|中国默认")
                this.setLocation("23.258702000001627,113.28866699999783|广州市白云区")
            }
            setTimeout(() => {
                this.getLocation()
            }, 3000);
        }
    }

    // 23.258702000001627,113.28866699999783|广州市白云区
    public static setLocation(locationStr: string) {
        // Logger.log("setLocation", locationStr)
        if (UserModel.instance.locationStr && UserModel.instance.locationStr != "") {
            SocketClient.req_set_location(locationStr)
        } else {
            let tmpstr = locationStr
            let arr: Array<string> = locationStr.split('|')
            if (arr.length == 2) {
                let addr: string = arr[1]
                let idx: number = addr.indexOf('区')
                if (idx > 0) {
                    addr = addr.slice(0, idx + 1)
                    tmpstr = arr[0] + '|' + addr;
                } else {
                    idx = addr.indexOf('县')
                    if (idx > 0) {
                        addr = addr.slice(0, idx + 1)
                        tmpstr = arr[0] + '|' + addr;
                    } else {
                        idx = addr.indexOf('市')
                        if (idx > 0) {
                            addr = addr.slice(0, idx + 1)
                            tmpstr = arr[0] + '|' + addr;
                        }
                    }
                }
                UserModel.instance.locationName = addr
            }
            UserModel.instance.locationStr = tmpstr
        }
    }


    public static selectPhoto(select_Pic_Type: number) {
        this.upload_pic_type = select_Pic_Type
        Logger.log("selectPhoto");
        if (cc.sys.isNative) {
            let clipX: number = 100;
            let clipY: number = 100;
            let tmpPath: string = jsb.fileUtils.getWritablePath() + 'tmpPhoto.jpg';
            let dict = {
                needClip: 1, //1是裁剪，2是不裁剪
                clipX: clipX, //裁剪x尺寸
                clipY: clipY, //裁剪y尺寸
                tmpPath: tmpPath
            }
            if (cc.sys.os == cc.sys.OS_ANDROID) {
                jsb.reflection.callStaticMethod("com/jhaosdk/ImagePicker", "selectPhoto", "(Ljava/lang/String;)V", JSON.stringify(dict));
                // jsb.reflection.callStaticMethod("com/jhaosdk/NativeSdkHelper", "selectPhoto", "(Ljava/lang/String;)V", JSON.stringify(dict));
            } else if (cc.sys.os == cc.sys.OS_IOS) {
                jsb.reflection.callStaticMethod("NativeSdkHelper", "openAlbumToWriteWithWritePath:", JSON.stringify(dict));
            }
        }
    }

    public static onSelectPhoto_callback(filePath: string) {
        Logger.log("onSelectPhoto_callback===", filePath)
        // let fileData = jsb.fileUtils.getDataFromFile(filePath);
        // Logger.log("base64Str=11=", fileData)
        // let base64Str: string = Uint8ArrayHelper.uint8arrayToBase64(fileData)
        // Logger.log("base64Str=22=", base64Str)
        // SocketClient.req_upload_img(this.upload_pic_type, base64Str)
    }


    public static pay(payInfo: string) {
        // Logger.log("pay=", payInfo)
        if (this.isAndroid()) {
            let relt: string = jsb.reflection.callStaticMethod('com/jhaosdk/PaySdkHelper', "payByThirdalipay", "(Ljava/lang/String;)Ljava/lang/String;", payInfo);
        } else if (this.isIos()) {
            jsb.reflection.callStaticMethod("NativeSdkHelper", "pay:", payInfo);
        }
    }

    public static save2PhotoAlbum(picPath: string) {
        Logger.info("JsNativeBridge.saveToNativeAlbum=", picPath);
        if (sys.isNative) {
            if (this.isIos()) {
                native.reflection.callStaticMethod("NativeSdkHelper", "save2PhotoAlbum:", picPath);
            } else if (this.isAndroid()) {
                native.reflection.callStaticMethod("org/cocos2dx/javascript/NativeSdkHelper", "save2PhotoAlbum", "(Ljava/lang/String;)V", picPath);
            }
        }
    }

    public static save2PhotoAlbumResp(msg: string) {
        Logger.log("save2PhotoAlbumResp=", msg)
    }
}

